package com.david.musicapp.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;

import com.david.core.event.MyEventBus;
import com.david.core.utils.ImageUtils;
import com.david.musicapp.MusicApplication;
import com.david.musicapp.R;
import com.david.musicapp.bean.Song;
import com.david.musicapp.event.SongListChangeEvent;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;

public class LocalMusicUtils {
    //定义一个集合，存放从本地读取到的内容
    public static ArrayList<Song> list = SongUtils.getStorageEntities(MusicApplication.Companion.instance(), "songsList");

//    public static Song song;
//    private static String name;
//    private static String singer;
//    private static String path;
//    private static int duration;
//    private static long size;
//    private static long albumId;
//    private static long id;
    //获取专辑封面的Uri
    private static final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");

    public static void getMusic() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                ArrayList<Song> list = new ArrayList<>();

                Cursor cursor = MusicApplication.Companion.instance().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                        , null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

                if (cursor != null) {
                    Song song;
                    while (cursor.moveToNext()) {

                        song = new Song();
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));

                        long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                        String singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                        if (new File(path).exists()) {//歌曲可能不存在，
                            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                            long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                            long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
                            //list.add(song);
                            //把歌曲名字和歌手切割开
                            //song.setName(name);
                            song.setSinger(singer);
                            song.setPath(path);
                            song.setDuration(duration);
                            song.setSize(size);
                            song.setId(id);
                            song.setAlbumId(albumId);
                            song.setAlbumImgPath(getAlbumArt(MusicApplication.Companion.instance(), albumId));


                            if (singer == null || "<unknown>".equals(singer) || name.contains("-")) {
                                if (name.contains("-")) {
                                    String[] str = name.split("-");
                                    singer = str[0].trim();
                                    song.setSinger(singer);
                                    name = str[1].trim();
                                    song.setName(name.trim());
                                } else {
                                    song.setName(name.trim());
                                    song.setSinger(name.trim().substring(0,name.lastIndexOf(".")));
                                }
                            } else {
                                song.setName(name.trim());
                                song.setSinger(name.trim().substring(0,name.lastIndexOf(".")));
                            }

                            list.add(song);
                        }
                    }
                    if (list.size() > 0) {
                        Collections.sort(list);
                        while ('#' == (list.get(0).sortChar)) {
                            Song tempSong = list.remove(0);
                            list.add(tempSong);
                        }
                    }
                    boolean songListChanged = false;
                    if (LocalMusicUtils.list == null || LocalMusicUtils.list.size() != list.size()) {
                        songListChanged = true;
                    }

                    if (!songListChanged) {
                        for(int i = 0; i<LocalMusicUtils.list.size();++i){
                            if (!LocalMusicUtils.list.get(i).equals(list.get(i))) {
                                songListChanged = true;
                                break;
                            }
                        }
                    }

                    if (songListChanged) {
                        LocalMusicUtils.list = list;
                        if (SongHelper.Companion.getInstance().getCurrentType() == 0) {
                            SongHelper.Companion.getInstance().setCurrentList(list);
                        }
                        SongUtils.saveStorage2SDCard(MusicApplication.Companion.instance(), list, "songsList");
                        MyEventBus.getDefault().post(new SongListChangeEvent());
                    }

                }
                cursor.close();
            }
        }.start();
    }

    //    转换歌曲时间的格式
    public static String formatTime(int time) {
        if (time / 1000 % 60 < 10) {
            String tt = time / 1000 / 60 + ":0" + time / 1000 % 60;
            return tt;
        } else {
            String tt = time / 1000 / 60 + ":" + time / 1000 % 60;
            return tt;
        }
    }

    /**
     * 获取专辑封面位图对象
     */
    public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefalut, boolean small){
        if(album_id < 0) {
            if(song_id < 0) {
                Bitmap bm = getArtworkFromFile(context, song_id, -1);
                if(bm != null) {
                    return bm;
                }
            }
            if(allowdefalut) {
                return getDefaultArtwork(context, small);
            }
            return null;
        }
        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(albumArtUri, album_id);
        if(uri != null) {
            InputStream in = null;
            try {
                in = res.openInputStream(uri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                //先制定原始大小
                options.inSampleSize = 1;
                //只进行大小判断
                options.inJustDecodeBounds = true;
                //调用此方法得到options得到图片的大小
                BitmapFactory.decodeStream(in, null, options);
                /** 我们的目标是在你N pixel的画面上显示。 所以需要调用computeSampleSize得到图片缩放的比例 **/
                /** 这里的target为800是根据默认专辑图片大小决定的，800只是测试数字但是试验后发现完美的结合 **/
                if(small){
                    options.inSampleSize = computeSampleSize(options, 40);
                } else{
                    options.inSampleSize = computeSampleSize(options, 600);
                }
                // 我们得到了缩放比例，现在开始正式读入Bitmap数据
                options.inJustDecodeBounds = false;
                options.inDither = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                in = res.openInputStream(uri);
                return BitmapFactory.decodeStream(in, null, options);
            } catch (FileNotFoundException e) {
                Bitmap bm = getArtworkFromFile(context, song_id, album_id);
                if(bm != null) {
                    if(bm.getConfig() == null) {
                        bm = bm.copy(Bitmap.Config.RGB_565, false);
                        if(bm == null && allowdefalut) {
                            return getDefaultArtwork(context, small);
                        }
                    }
                } else if(allowdefalut) {
                    bm = getDefaultArtwork(context, small);
                }
                return bm;
            } finally {
                try {
                    if(in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 从文件当中获取专辑封面位图
     */
    private static Bitmap getArtworkFromFile(Context context, long songid, long albumid){
        Bitmap bm = null;
        if(albumid < 0 && songid < 0) {
            throw new IllegalArgumentException("Must specify an album or a song id");
        }
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            FileDescriptor fd = null;
            if(albumid < 0){
                Uri uri = Uri.parse("content://media/external/audio/media/"
                        + songid + "/albumart");
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if(pfd != null) {
                    fd = pfd.getFileDescriptor();
                }
            } else {
                Uri uri = ContentUris.withAppendedId(albumArtUri, albumid);
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if(pfd != null) {
                    fd = pfd.getFileDescriptor();
                }
            }
            options.inSampleSize = 1;
            // 只进行大小判断
            options.inJustDecodeBounds = true;
            // 调用此方法得到options得到图片大小
            BitmapFactory.decodeFileDescriptor(fd, null, options);
            // 我们的目标是在800pixel的画面上显示
            // 所以需要调用computeSampleSize得到图片缩放的比例
            options.inSampleSize = 100;
            // 我们得到了缩放的比例，现在开始正式读入Bitmap数据
            options.inJustDecodeBounds = false;
            options.inDither = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;

            //根据options参数，减少所需要的内存
            bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bm;
    }

    /**
     * 获取默认专辑图片
     */
    public static Bitmap getDefaultArtwork(Context context,boolean small) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        if(small){    //返回小图片
            //return
            BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_logo);
        }
        //return BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.defaultalbum), null, opts);
        return null;
    }

    /**
     * 对图片进行合适的缩放
     */
    public static int computeSampleSize(BitmapFactory.Options options, int target) {
        int w = options.outWidth;
        int h = options.outHeight;
        int candidateW = w / target;
        int candidateH = h / target;
        int candidate = Math.max(candidateW, candidateH);
        if(candidate == 0) {
            return 1;
        }
        if(candidate > 1) {
            if((w > target) && (w / candidate) < target) {
                candidate -= 1;
            }
        }
        if(candidate > 1) {
            if((h > target) && (h / candidate) < target) {
                candidate -= 1;
            }
        }
        return candidate;
    }

    /**
     * 根据专辑ID获取专辑封面图
     * @param album_id 专辑ID
     * @return
     */
    public static String getAlbumArt(Context context, long album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = context.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Long.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        String path = null;
        if (album_art != null) {
            path = album_art;
        } else {
            //path = "drawable/music_no_icon.png";
            //bm = BitmapFactory.decodeResource(getResources(), R.drawable.default_cover);
        }
        return path;
    }


    private static String currentMediaUri = "";
    private static Bitmap currentBitmap = null;

    /**
     * 加载封面
     * @param mediaUri MP3文件路径
     */
    public static Bitmap loadingCover(String mediaUri) {
        return null;
//        if (!new File(mediaUri).exists()) {
//            return null;
//        }
//        try {
//            MediaMetadataRetriever mediaMetadataRetriever=new MediaMetadataRetriever();
//            mediaMetadataRetriever.setDataSource(mediaUri);
//
//            byte[] picture = mediaMetadataRetriever.getEmbeddedPicture();
//            if (picture == null) {
//                return null;
//            }
//
//            Bitmap bitmap= BitmapFactory.decodeByteArray(picture,0,picture.length);
//            return ImageUtils.toRoundCorner(bitmap, 50);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
    }
}